﻿using System;
using Ch.Admin.Bfs.Sms.Sdmx.Common;
using Ch.Admin.Bfs.Sms.Sdmx.Registry.Rights;
using Ch.Admin.Bfs.Sms.Sdmx.Schemes;
using System.Collections.Generic;

namespace SdmxMl.Multiplexor
{
    /// <summary>
    /// Helper class for obtaining owner groups filtered by User Id
    /// </summary>
    public class OwnerHelper
    {
        #region Internal Members

        private ISecuredArtefactRegistry artefactRegistry;
        private OrganisationUnitScheme orgUnit;

        #endregion

        #region Constructor

        public OwnerHelper(ISecuredArtefactRegistry secureRegistry)
        {
            artefactRegistry = secureRegistry;
            MaintainableArtefactReference reference = new MaintainableArtefactReference(ArtefactType.OrganisationUnitScheme, "CH1+OWNERS+1.0");
            orgUnit = artefactRegistry.Get(reference) as OrganisationUnitScheme;
            if (orgUnit == null)
                throw new ApplicationException("Unable to obtain Organisation Unit Scheme: " + reference.FullIdentifier);
        }
        #endregion

        #region Get Owner list

        /// <summary> Gets list of Owner group where user is part of </summary>
        /// <param name="userId">the window user, like: (adb\U7654243) </param>
        /// <remarks>if userId parameter is set to null, the full list is returned</remarks>
        /// <returns>the list of owner group related to user</returns>
        public List<string> GetUserUnits(string userId)
        {
            List<string> list = new List<string>();
            foreach (OrganisationUnit org in orgUnit.Units)
            {
                    foreach (Contact c in org.Contacts)
                    {
                        if (userId == null || (c.Department.DefaultText + c.Identifier).ToLower() == userId.ToLower())
                            if (list.Contains(org.Identifier) == false)
                                list.Add(org.Identifier);
                    }
                
            }
            return list;
        }
        #endregion
    }
}
